import { Get, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { DeepPartial, Repository } from 'typeorm';
import { User } from './models/user.entity';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User) private UserRepository: Repository<User>,
  ) {}
  /**
   * 新增用户
   * @param entity
   * @returns
   */
  async create(entity: DeepPartial<User>): Promise<boolean> {
    const res = await this.UserRepository.insert(entity);
    if (res && res.raw.affectedRows > 0) {
      return true;
    } else {
      return false;
    }
  }
  /**
   * 删除用户
   * @param id
   * @returns
   */
  async del(id: string): Promise<boolean> {
    const res = await this.UserRepository.delete(id);
    if (
      res?.affected !== null &&
      res?.affected !== undefined &&
      res.affected > 0
    ) {
      return true;
    } else {
      return false;
    }
  }
  /**
   * 更新用户
   * @param id
   * @param entity
   * @returns
   */
  async update(id: string, entity: DeepPartial<User>): Promise<boolean> {
    const res = await this.UserRepository.update(id, entity);
    if (
      res?.affected !== null &&
      res?.affected !== undefined &&
      res.affected > 0
    ) {
      return true;
    } else {
      return false;
    }
  }
  /**
   * 查询用户
   * @param id 可选的用户ID
   * @returns 用户信息或null
   */
  async find(id?: string): Promise<User | null> {
    if (!id) {
      return null;
    }
    const res = await this.UserRepository.findOne({
      where: {
        id,
      },
    });
    return res ?? null;
  }
}
